#ifndef PROFILE_H
#define PROFILE_H

#include "m_fhs.h"
#include "m_type.h"
#include "head/g_functionbase.h"

struct User
{
    QString name,passwd,token,group;
    int level;
};

class Profile : public QObject
{
    Q_OBJECT
public:
    explicit Profile(QObject *parent = nullptr): QObject(parent)
    {
        user.level=USER_LEVEL_USER;
    }

    void loadProfile(const QString &userLand)
    {
        auto filePath=userLand + QString("/") + USER_FILE;
        auto cborValue=sp_readCborFromFile(filePath);
        if(cborValue.isMap())
        {
            auto cborMap=cborValue.toMap();
            user.name=cborMap.value("name").toString();
            user.passwd=cborMap.value("passwd").toString();
            user.token=cborMap.value("token").toString();
            user.group=cborMap.value("group").toString();
            user.level=cborMap.value("level").toInteger();
        }
    }

    void setUserInfo(const User &user_){
        this->user = user_;
        auto payload = user_.name + user_.passwd;
        user.passwd = QCryptographicHash::hash(payload.toUtf8(),
                                               QCryptographicHash::Sha1).toHex();
    }

    User getUserInfo() const{
        return user;
    }

    void saveProfile(const QString &userLand){
        auto filePath=userLand + QString("/") + USER_FILE;
        QCborMap map={
            {"name",user.name},
            {"passwd",user.passwd},
            {"token",user.token},
            {"group",user.group},
            {"level",user.level}
        };

        sp_writeCborToFile(QCborValue(map),filePath);
    }

private:
    User user;
};


#endif // PROFILE_H
